package com.bcu.cn.onlineexamsystem.grademanage.controller;

import com.bcu.cn.onlineexamsystem.grademanage.service.TeacherScoreAnalysisService;
import com.bcu.cn.onlineexamsystem.user.entity.User;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 教师端成绩分析控制器
 */
@Controller
@RequestMapping("/teacher/score")
public class TeacherScoreAnalysisController {
    
    private static final Logger logger = LoggerFactory.getLogger(TeacherScoreAnalysisController.class);
    
    @Autowired
    private TeacherScoreAnalysisService teacherScoreAnalysisService;
    
    /**
     * 获取当前登录的教师ID
     */
    private String getCurrentTeacherId(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            logger.error("用户未登录");
            throw new RuntimeException("用户未登录");
        }
        if (!"teacher".equals(user.getRole())) {
            logger.error("非教师用户，无权访问");
            throw new RuntimeException("非教师用户，无权访问");
        }
        return user.getUserId();
    }
    
    /**
     * 成绩分析主页面
     */
    @GetMapping("/analysis")
    public String scoreAnalysisPage(HttpSession session, Model model) {
        logger.info("=== 教师端成绩分析页面访问开始 ===");
        
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}", teacherId);
            
            // 获取基础统计数据
            var statistics = teacherScoreAnalysisService.getScoreStatistics();
            logger.info("获取统计数据成功: {}", statistics);
            model.addAttribute("statistics", statistics);
            
            logger.info("=== 教师端成绩分析页面访问结束 ===");
            return "teacher/score/analysis";
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            model.addAttribute("error", "获取统计数据失败: " + e.getMessage());
            return "teacher/score/analysis";
        }
    }
    
    /**
     * 获取成绩统计数据API
     */
    @GetMapping("/api/statistics")
    @ResponseBody
    public Map<String, Object> getStatistics(HttpSession session) {
        logger.info("=== API调用: 获取教师端统计数据 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}", teacherId);
            
            var statistics = teacherScoreAnalysisService.getScoreStatistics();
            logger.info("统计数据获取成功: {}", statistics);
            
            result.put("success", true);
            result.put("data", statistics);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            result.put("success", false);
            result.put("message", "获取统计数据失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取成绩趋势数据API
     */
    @GetMapping("/api/trend")
    @ResponseBody
    public Map<String, Object> getScoreTrend(HttpSession session) {
        logger.info("=== API调用: 获取教师端趋势数据 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}", teacherId);
            
            var trendData = teacherScoreAnalysisService.getScoreTrend();
            logger.info("趋势数据获取成功: {}", trendData);
            
            result.put("success", true);
            result.put("data", trendData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取趋势数据失败", e);
            result.put("success", false);
            result.put("message", "获取趋势数据失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取成绩分布数据API
     */
    @GetMapping("/api/distribution")
    @ResponseBody
    public Map<String, Object> getScoreDistribution(HttpSession session) {
        logger.info("=== API调用: 获取教师端分布数据 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}", teacherId);
            
            var distributionData = teacherScoreAnalysisService.getScoreDistribution();
            logger.info("分布数据获取成功: {}", distributionData);
            
            result.put("success", true);
            result.put("data", distributionData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取分布数据失败", e);
            result.put("success", false);
            result.put("message", "获取分布数据失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取课程成绩分析API
     */
    @GetMapping("/api/course-analysis")
    @ResponseBody
    public Map<String, Object> getCourseAnalysis(HttpSession session) {
        logger.info("=== API调用: 获取教师端课程分析 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}", teacherId);
            
            var courseData = teacherScoreAnalysisService.getCourseScoreAnalysis();
            logger.info("课程分析数据获取成功: {}", courseData);
            
            result.put("success", true);
            result.put("data", courseData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取课程分析失败", e);
            result.put("success", false);
            result.put("message", "获取课程分析失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取学生成绩排名API
     */
    @GetMapping("/api/student-ranking")
    @ResponseBody
    public Map<String, Object> getStudentRanking(HttpSession session) {
        logger.info("=== API调用: 获取教师端学生排名 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}", teacherId);
            
            var rankingData = teacherScoreAnalysisService.getStudentRanking();
            logger.info("学生排名数据获取成功: {}", rankingData);
            
            result.put("success", true);
            result.put("data", rankingData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取学生排名失败", e);
            result.put("success", false);
            result.put("message", "获取学生排名失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取最近考试记录API
     */
    @GetMapping("/api/recent-records")
    @ResponseBody
    public Map<String, Object> getRecentRecords(@RequestParam(defaultValue = "5") Integer limit, HttpSession session) {
        logger.info("=== API调用: 获取教师端最近记录 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}, 限制数量: {}", teacherId, limit);
            
            var records = teacherScoreAnalysisService.getRecentExamRecords(limit);
            logger.info("最近记录获取成功: {}", records);
            
            result.put("success", true);
            result.put("data", records);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取最近记录失败", e);
            result.put("success", false);
            result.put("message", "获取最近记录失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取考试详情API
     */
    @GetMapping("/api/exam-detail/{examId}")
    @ResponseBody
    public Map<String, Object> getExamDetail(@PathVariable Long examId, HttpSession session) {
        logger.info("=== API调用: 获取教师端考试详情 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}, 考试ID: {}", teacherId, examId);
            
            var examDetail = teacherScoreAnalysisService.getExamDetail(examId);
            logger.info("考试详情获取成功: {}", examDetail);
            
            result.put("success", true);
            result.put("data", examDetail);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取考试详情失败", e);
            result.put("success", false);
            result.put("message", "获取考试详情失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 考试详情页面
     */
    @GetMapping("/detail/{examId}")
    public String examDetailPage(@PathVariable Long examId, HttpSession session, Model model) {
        logger.info("=== 教师端考试详情页面访问 ===");
        
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}, 考试ID: {}", teacherId, examId);
            
            var examDetail = teacherScoreAnalysisService.getExamDetail(examId);
            logger.info("考试详情获取成功: {}", examDetail);
            
            model.addAttribute("examDetail", examDetail);
            model.addAttribute("examId", examId);
            
            return "teacher/score/exam-detail";
        } catch (Exception e) {
            logger.error("获取考试详情失败", e);
            model.addAttribute("error", "获取考试详情失败: " + e.getMessage());
            return "teacher/score/exam-detail";
        }
    }
    
    /**
     * 课程成绩分析页面
     */
    @GetMapping("/course")
    public String courseScorePage(HttpSession session, Model model) {
        logger.info("=== 教师端课程成绩页面访问 ===");
        
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}", teacherId);
            
            var courseData = teacherScoreAnalysisService.getCourseScoreAnalysis();
            logger.info("课程数据获取成功: {}", courseData);
            
            model.addAttribute("courseData", courseData);
            
            return "teacher/score/course";
        } catch (Exception e) {
            logger.error("获取课程数据失败", e);
            model.addAttribute("error", "获取课程数据失败: " + e.getMessage());
            return "teacher/score/course";
        }
    }
    
    /**
     * 学生排名页面
     */
    @GetMapping("/ranking")
    public String studentRankingPage(HttpSession session, Model model) {
        logger.info("=== 教师端学生排名页面访问 ===");
        
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}", teacherId);
            
            var rankingData = teacherScoreAnalysisService.getStudentRanking();
            logger.info("学生排名数据获取成功: {}", rankingData);
            
            model.addAttribute("rankingData", rankingData);
            
            return "teacher/score/ranking";
        } catch (Exception e) {
            logger.error("获取学生排名失败", e);
            model.addAttribute("error", "获取学生排名失败: " + e.getMessage());
            return "teacher/score/ranking";
        }
    }
    
    /**
     * 获取教师课程列表API
     */
    @GetMapping("/api/teacher-courses")
    @ResponseBody
    public Map<String, Object> getTeacherCourses(HttpSession session) {
        logger.info("=== API调用: 获取教师课程列表 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}", teacherId);
            
            var courses = teacherScoreAnalysisService.getTeacherCourses(teacherId);
            logger.info("教师课程列表获取成功: {}", courses);
            
            result.put("success", true);
            result.put("data", courses);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取教师课程列表失败", e);
            result.put("success", false);
            result.put("message", "获取教师课程列表失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 根据课程ID获取成绩统计数据API
     */
    @GetMapping("/api/statistics/{courseId}")
    @ResponseBody
    public Map<String, Object> getStatisticsByCourse(@PathVariable Long courseId, HttpSession session) {
        logger.info("=== API调用: 获取课程成绩统计数据 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}, 课程ID: {}", teacherId, courseId);
            
            var statistics = teacherScoreAnalysisService.getScoreStatisticsByCourse(courseId);
            logger.info("课程统计数据获取成功: {}", statistics);
            
            result.put("success", true);
            result.put("data", statistics);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取课程统计数据失败", e);
            result.put("success", false);
            result.put("message", "获取课程统计数据失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 根据课程ID获取成绩趋势数据API
     */
    @GetMapping("/api/trend/{courseId}")
    @ResponseBody
    public Map<String, Object> getScoreTrendByCourse(@PathVariable Long courseId, HttpSession session) {
        logger.info("=== API调用: 获取课程成绩趋势数据 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}, 课程ID: {}", teacherId, courseId);
            
            var trendData = teacherScoreAnalysisService.getScoreTrendByCourse(courseId);
            logger.info("课程趋势数据获取成功: {}", trendData);
            
            result.put("success", true);
            result.put("data", trendData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取课程趋势数据失败", e);
            result.put("success", false);
            result.put("message", "获取课程趋势数据失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 根据课程ID获取成绩分布数据API
     */
    @GetMapping("/api/distribution/{courseId}")
    @ResponseBody
    public Map<String, Object> getScoreDistributionByCourse(@PathVariable Long courseId, HttpSession session) {
        logger.info("=== API调用: 获取课程成绩分布数据 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}, 课程ID: {}", teacherId, courseId);
            
            var distributionData = teacherScoreAnalysisService.getScoreDistributionByCourse(courseId);
            logger.info("课程分布数据获取成功: {}", distributionData);
            
            result.put("success", true);
            result.put("data", distributionData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取课程分布数据失败", e);
            result.put("success", false);
            result.put("message", "获取课程分布数据失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 根据课程ID获取学生成绩排名API
     */
    @GetMapping("/api/student-ranking/{courseId}")
    @ResponseBody
    public Map<String, Object> getStudentRankingByCourse(@PathVariable Long courseId, HttpSession session) {
        logger.info("=== API调用: 获取课程学生成绩排名 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}, 课程ID: {}", teacherId, courseId);
            
            var rankingData = teacherScoreAnalysisService.getStudentRankingByCourse(courseId);
            logger.info("课程学生排名数据获取成功: {}", rankingData);
            
            result.put("success", true);
            result.put("data", rankingData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取课程学生排名失败", e);
            result.put("success", false);
            result.put("message", "获取课程学生排名失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 根据课程ID获取最近考试记录API
     */
    @GetMapping("/api/recent-records/{courseId}")
    @ResponseBody
    public Map<String, Object> getRecentRecordsByCourse(@PathVariable Long courseId, @RequestParam(defaultValue = "5") Integer limit, HttpSession session) {
        logger.info("=== API调用: 获取课程最近考试记录 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String teacherId = getCurrentTeacherId(session);
            logger.info("教师ID: {}, 课程ID: {}, 限制数量: {}", teacherId, courseId, limit);
            
            var records = teacherScoreAnalysisService.getRecentExamRecordsByCourse(courseId, limit);
            logger.info("课程最近记录获取成功: {}", records);
            
            result.put("success", true);
            result.put("data", records);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取课程最近记录失败", e);
            result.put("success", false);
            result.put("message", "获取课程最近记录失败：" + e.getMessage());
        }
        
        return result;
    }
} 